import java.util.Arrays;
import java.util.HashMap;
//存在问题

public class Solution517 {
    public int findMinMoves(int[] machines) {
        int sum = 0;
        int count = 0;
        for (int i = 0; i < machines.length; i++) {
            sum += machines[i];
            if (machines[i] != 0) count++;
        }
        if (sum % machines.length != 0) return -1;
        int avg = sum / machines.length;
        if (count == 1) {
            int t = 0;
            for (int i = 0; i < machines.length - 1; i++) {
                if (machines[i] != avg) {
                    int moveCloth = machines[i] - avg;
                    machines[i] -= moveCloth;
                    machines[i + 1] += moveCloth;
                    t++;
                }
            }
            return t;
        }
        //Arrays.sort(machines);
        int max = 0;
        int temp=0;
        for (int i = 0; i < machines.length - 1; i++) {
            int coun = 0;
            int subSum = 0;
            for (int j = i; j < machines.length; j++) {
                if (machines[j] != 0) coun++;
                subSum += machines[j];
            }
            if (coun == 1) {
                int t = 0;
                int subAvg=subSum/(machines.length-i);
                for (int s = i; s < machines.length - 1; s++) {
                    if (machines[s] != subAvg) {
                        int moveCloth = machines[s] - subAvg;
                        machines[s] -= moveCloth;
                        machines[s + 1] += moveCloth;
                        t+=Math.abs(moveCloth);
                    }
                }
                return Math.max(t,max);
            }
            if (machines[i] != avg) {
                int moveCloth = machines[i] - avg;
                machines[i] -= moveCloth;
                machines[i + 1] += moveCloth;
                temp++;
                if (max < Math.abs(moveCloth)) {
                    max = Math.abs(moveCloth);
                }
            }
        }
        //return max;
        return Math.max(max,temp);
    }

    public static void main(String[] args) {
        Solution517 solution517 = new Solution517();
        System.out.println(solution517.findMinMoves(new int[]{
                0, 3, 0
        }));
        System.out.println(solution517.findMinMoves(new int[]{
                1, 0, 5
        }));
        System.out.println(solution517.findMinMoves(new int[]{
                4, 0, 0, 4
        }));
        System.out.println(solution517.findMinMoves(new int[]{
                0, 4, 12, 0
        }));
        System.out.println(solution517.findMinMoves(new int[]{
                0, 0, 0, 4
        }));
        System.out.println(solution517.findMinMoves(new int[]{
                2,4,8,4,2
        }));
        System.out.println(solution517.findMinMoves(new int[]{
                0,0,10,0,0,0,10,0,0,0
        }));
    }

}
